﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Actya.Web.Infrastructure.ElFinderConnector.Responses;
using Actya.Web.Infrastructure.ElFinderConnector.Utils;
using System.Diagnostics;
namespace Actya.Web.Infrastructure.ElFinderConnector.Commands
{
    public class Archive : ICommand
    {
        public string Current { get; set; }

        public string Type { get; set; }

        public IEnumerable<string> Targets { get; set; }

        public Archive(string current, string type, string targets)
        {
            this.Current = current;

            this.Type = type;

            this.Targets = targets.Split(",".ToCharArray());
        }

        #region ICommand Members

        public Response Execute()
        {
            var path = DirectoryUtils.GetRelativePathByHash(Current);

            

            var response = new Responses.ActionCompletedResponse();

            var ArcApp = Configuration.Configuration.ArcAppPath;

            //response.tree = folder.Tree;

            string ArcName = "";
            if (Targets.Count() == 1)
            {
                ArcName = new System.IO.DirectoryInfo(DirectoryUtils.GetFilePathByHash(Targets.First())).Name;
            }
            else
            {
                ArcName = "Archive1.7z";
            }

            System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("\"" + ArcApp + "\"");
            psi.RedirectStandardOutput = true;
            psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            psi.UseShellExecute = false;
            
            

            foreach (string hashname in Targets)
            {
                string filename = DirectoryUtils.GetFilePathByHash(hashname);
                psi.Arguments = " a " + path + @"\" + ArcName + ".7z" + " " + filename + " -r ";
                var proc = Process.Start(psi);
                proc.WaitForExit(10000);
            }

            var folder = new Utils.Folder(path);

            response.select = new string[] { (path + @"\" + "Archive1.7z").Hash() };

            response.cwd = folder.Cwd;

            response.cdc = folder.Contents;

            return response;
        }

        #endregion
    }
}
